﻿using IBLL;
using IDAL;
using Model;

namespace BLL
{
    public class UserBLL : IUserBLL
    {
        public UserBLL(IBaseDAL<UserModel> dal)
        {
            Dal = dal;
        }

        public IBaseDAL<UserModel> Dal { get; }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> AddUser(UserModel model)
        {
            return await Dal.AddAsync(model);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        public dynamic GetAll(int PageSize, int PageIndex)
        {
            var q = Dal.QueryAsync();
            return new
            {
                count = q.Count(),
                data = q.OrderBy(x => x.Id).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList()
            };
        }
        /// <summary>
        /// 根据Id查所有
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserModel GetAllUser(int id)
        {
            return Dal.QueryAsync().FirstOrDefault(x => x.Id == id);
        }
        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="Delstring"></param>
        /// <returns></returns>
        public async Task<int> UpdateUser(string Delstring)
        {
            List<int> ids = Delstring.Split(',').Select(x=>Convert.ToInt32(x)).ToList();
            var h = Dal.QueryAsync().Where(x=>ids.Contains(x.Id)).ToList();
            foreach(var iteam in h)
            {
                iteam.isDel = 2;
            }
            return await Dal.UpdateAsync(h);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="UserZH"></param>
        /// <param name="UserPwd"></param>
        /// <returns></returns>
        public UserModel UserLogin(string UserZH, string UserPwd)
        {
            var s = Dal.QueryAsync().FirstOrDefault(x => x.UserZH == UserZH);
            if (s == null)
            {
                s = new UserModel { Id = -1 };
            }
            else
            {
                if (s.UserPwd != UserPwd)
                {
                    s = new UserModel { Id = -2 };
                }
            }
            return s;
        }
    }
}
